var crypto = require('crypto'),//加密组件
     User = require('../models/user.js'),
     Hotel = require('../models/hotel.js'),
    Countries = require('../models/countries.js');


module.exports= function(app){
    app.get("/",function(req,res){
        //var page = req.query.p? req.query.p :1;
        Countries.getTen(function(err,countries){
            if(err){
                countries = [];
            }
            res.render("index",{
                 title:"主页",
                 user: req.session.user,
                 countries: countries
             });
        });
    });

    app.get("/login",checkNotLogin);
    app.get("/login",function(req,res){
         res.render("login",{
             title:"用户登录"
        });
    });

    app.post("/login",checkNotLogin);
    app.post("/login",function(req,res){
        var md5 = crypto.createHash("md5"),
            password = md5.update(req.body.password).digest("hex");
        User.get(req.body.name, function (err, user) {
            if(!user){
                req.flash("error","用户不存在");
                return res.redirect("/login");
            }
            if(password != user.password){
                req.flash("error","密码错误")
                return res.redirect("/login");
            }
            req.session.user = user;
            req.flash('success', '登陆成功!');
            res.redirect('/');
        });

    });


    function checkLogin(req,res,next){
       if(!req.session.user){
           res.redirect("/login");
       }
       next();
    }

    function checkNotLogin(req,res,next){
        if(req.session.user){
            console.log(req.session.user);
            res.redirect("back");
        }
        next();
    }


}


